<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!--  显示供应商列表-->
    <el-table style="width: 100%" :data="pagedManufacturer">
      <!--      表单目录-->
      <el-table-column prop="new_i" label="编号" width="80"/>
      <el-table-column prop="name" label="名称"/>
      <el-table-column prop="phone" label="电话"/>
      <el-table-column prop="address" label="地址"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope" v-if="haspermission(['admin','manager'])">
          <div style="display: flex;align-items: center;">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端数据库修改供应商数据:</p>
                  <label>名字：</label>
                  <el-input
                      v-model="ManufacturerEdit.name"
                      style="width: 240px"
                      maxlength="15"
                      show-word-limit
                      type="text"
                  />
                  <div style="margin: 10px 0"/>
                  <label>电话：</label>
                  <el-input
                      v-model="ManufacturerEdit.phone"
                      maxlength="15"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  />
                  <div style="margin: 10px 0"/>
                  <label>地址：</label>
                  <el-input
                      v-model="ManufacturerEdit.address"
                      maxlength="15"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  />
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />
    <!--  添加供应商数据的表单-->
    <div style="display: flex; align-items: center;">
      <form @submit="ManufacturerSubmit" ref="myForm">
        <h3>向后端数据库添加供应商数据:</h3>
        <label>名字：</label>
        <el-input
            v-model="inputManufacturer.name"
            style="width: 240px"
            maxlength="15"
            show-word-limit
            type="text"
        />
        <div style="margin: 10px 0"/>
        <label>电话：</label>
        <el-input
            v-model="inputManufacturer.phone"
            maxlength="15"
            style="width: 240px"
            show-word-limit
            type="text"
        />
        <div style="margin: 10px 0"/>
        <label>地址：</label>
        <el-input
            v-model="inputManufacturer.address"
            maxlength="15"
            style="width: 240px"
            show-word-limit
            type="text"
        />
        <div style="margin: 20px 0"/>
        <el-button type="success" round @click="ManufacturerSubmit">提交数据</el-button>
      </form>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询供应商的表单1</h3>
        <label>供应商名称：</label>
        <el-input type="text" style="width: 240px"/>
        <div style="margin: 20px 0"/>
        <el-button type="info">按名称查找</el-button>
      </div>
      <div style="padding: 5%"></div>
      <div>
        <h3>查询供应商的表单2</h3>
        <label>供应商地址：</label>
        <el-input type="text" style="width: 240px" />
        <div style="margin: 20px 0"/>
        <el-button type="info" >按地址查找</el-button>
      </div>
      <div style="padding: 5%"></div>
    </div>
  </div>
</template>


<script setup lang="ts">
import {onMounted, ref, h, computed, watch} from "vue";
import {getManufacturer, postManufacturer, deleteManufacturer, updateManufacturer} from "@/api/api";
import {ElMessage, ElMessageBox} from 'element-plus'
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref("欢迎来到供应商管理板块");


//增
const inputManufacturer = ref({
  name:"",
  phone:"",
  address:""
})

async function ManufacturerSubmit() {
  try {
    const response = await postManufacturer(inputManufacturer.value.name, inputManufacturer.value.phone, inputManufacturer.value.address);
    console.log(response);
    await loadManufacturer();
    inputManufacturer.value = {name: "", phone: "", address:""};
  } catch (error) {
    console.error('Error loading Manufacturer:', error);
  }
}


//delete
async function deleteManufacturerAndHandleResponse(id: number) {
  try {
    const response = await deleteManufacturer(id);
    console.log('Manufacturer deleted successfully', response);
    await loadManufacturer()
  } catch (error) {
    console.error('Error deleting Manufacturer', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: '消息通知',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteManufacturerAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//修改数据
const ManufacturerEdit = ref({
  name: "",
  phone: "",
  address:"",
})

function setValue(obj: any) {
  ManufacturerEdit.value.name = obj.name;
  ManufacturerEdit.value.phone = obj.phone;
  ManufacturerEdit.value.address = obj.address;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateManufacturer(obj.id, ManufacturerEdit.value)
    console.log("Manufacturer edit successfully", response)
    await loadManufacturer()
  } catch (error) {
    console.error(error);
  }
}

//查看所有
const Manufacturer = ref([
  {id: 1, name: "", phone: "", address:"",new_i: 0},
  {id: 2, name: "", phone: "", address:"",new_i: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(Manufacturer.value.length) // 计算总记录数

watch(Manufacturer, (newValue) => {
  total.value = newValue.length;
});
const pagedManufacturer = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return Manufacturer.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadManufacturer() {
  try {
    const response = await getManufacturer();
    Manufacturer.value = response.data;
    let new_index = 1;
    for (let oneManufacturer of Manufacturer.value) {
      oneManufacturer.new_i = new_index;
      new_index++;
    }
  } catch (error) {
    console.error('Error loading Manufacturer:', error);
  }
}

onMounted(() => {
  loadManufacturer();
})

</script>


<style scoped>

</style>